package se.hiq.wineo.client;

import se.hiq.wineo.client.widgets.WineListWidget;
import se.hiq.wineo.client.widgets.WineStatWidget;
import se.hiq.wineo.client.widgets.WineViewWidget;
import se.hiq.wineo.shared.data.WineDescriptor;
import se.hiq.wineo.shared.data.WineDetails;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class WineO implements EntryPoint {

	//Create a remote service proxy to talk to the server-side Greeting service.
	private final WineServiceAsync wineService = GWT.create(WineService.class);

	// Widgets
	private WineListWidget wineList = null;
	private WineViewWidget wineView = null;
	private WineStatWidget wineStat = null;
	
	// This is the entry point method.
	public void onModuleLoad() {
		// Run these first to reduce loading time of this applet
		requestCompleteWineList();
		requestWineDetails(6l);
		
		wineList = new WineListWidget();
		wineView = new WineViewWidget();
		wineStat = new WineStatWidget();
		
		RootPanel.get("wineList").add(wineList);
		RootPanel.get("wineView").add(wineView);
		RootPanel.get("wineStat").add(wineStat);
	}
	
	public void requestCompleteWineList() {
		wineService.getAvailableWines(new AsyncCallback<WineDescriptor[]>() {
			@Override
			public void onSuccess(WineDescriptor[] result) {
				// TODO: This is test code
				wineList.onCompleteWineList(result);
				wineStat.onCompleteWineList(result);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error: " + caught.toString());
			}
		});
	}
	
	public void requestWineDetails(Long primaryKey) {
		wineService.getWineDetails(primaryKey, new AsyncCallback<WineDetails>() {
			@Override
			public void onSuccess(WineDetails result) {
				// TODO: This is test code
				wineView.onWineSelected(result);
			}
			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Error: " + caught.toString());
			}
		});
	}
}
